<template>
  <div class="dataPower" v-loading="loading">
    <div class="search">
      <el-form ref="queryParamsRef" :model="form" label-width="80px" style="width: 20%">
        <el-form-item label="角色名称">
          <el-input v-model="form.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" icon="el-icon-search" class="createAppBtn" style="background: #2f54eb" @click="getList"
        size="small">查询</el-button>
      <el-button icon="el-icon-refresh-right" @click="handleReset" size="small">重置</el-button>
    </div>
    <div class="main">
      <div class="left">
        <el-table :data="roleList" border style="width: 100%" highlight-current-row @current-change="handleCurrentChange"
          :row-key="'value'">
          <el-table-column label="序号" width="80" align="center">
            <template slot-scope="scope">
              {{ (form.pageNum - 1) * form.pageSize + (scope.$index + 1) }}
            </template>
          </el-table-column>
          <el-table-column prop="roleName" label="角色名称" align="center">
          </el-table-column>
          <el-table-column prop="roleKey" label="权限字符" align="center">
          </el-table-column>
        </el-table>
        <div class="pagination">
          <pagination v-show="total > 0" :total="total" :page.sync="form.pageNum" :limit.sync="form.pageSize"
            @pagination="getList" />
        </div>
      </div>
      <div class="right">
        <el-table :data="listRight" border style="width: 100%" ref="multipleTable"
          @selection-change="handleSelectionChange">
          <el-table-column label=" " align="center" width="60">
            <template slot-scope="scope">
              <el-radio v-model="radio" :label="scope.row.value" @change.native="getCurrentRow(scope.row)">&nbsp;</el-radio>
            </template>
          </el-table-column>
          <!-- <el-table-column type="selection" width="55" align="center"> </el-table-column> -->
          <el-table-column prop="label" label="规则名称" align="center">
          </el-table-column>
          <el-table-column prop="date" label="系统规则" align="center" width="200" :formatter="() => '是'">
          </el-table-column>
        </el-table>
        <el-form ref="customPowerFormRef" :model="customPowerForm" label-width="80px" style="width: 100%">
          <el-form-item label="数据权限" v-if="radio === 'CUSTOM'">
            <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
            <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
            <el-checkbox v-model="deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
            <el-tree class="tree-border" :data="deptOptions" show-checkbox default-expand-all ref="dept" node-key="id"
              style="height:400px;overflow-y:auto" :check-strictly="!deptCheckStrictly" empty-text="加载中，请稍候"
              :props="defaultProps" :default-checked-keys="defaultCheckKeys" @check="deptPowerChange"></el-tree>
          </el-form-item>
          <el-form-item label="权限配置" v-if="radio === 'SELF'" label-width="80px" style="width: 100%;margin-top:20px">
            <el-row :gutter="20">
              <el-col :span="10"> <el-select v-model="customPowerForm.fieldLeft" placeholder="请选择" style="width: 100%"
                  @change="handleSelfChange">
                  <el-option :key="item.id" :label="item.label" :value="item.value"
                    v-for="item in dict.type.self_data_permission_category"></el-option></el-select></el-col>
              <el-col :span="2" style="text-align: center;">对应</el-col>
              <el-col :span="10"> <el-select v-model="customPowerForm.fieldRight" placeholder="请选择" style="width: 100%"
                  @change="handleSelfChange">
                  <el-option :key="item.field" :label="item.label" :value="item.field"
                    v-for="item in systemFieldList"></el-option>
                </el-select></el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script >
import {
  listRole,
  getRole,
  delRole,
  addRole,
  updateRole,
  dataScope,
  changeRoleStatus,
  deptTreeSelect,
  allocatedUserList,
  authUserCancel,
  authUserCancelAll,
} from "@/api/app/role";
export default {
  dicts: ["sys_data_power", 'self_data_permission_category'],
  props: {
    appId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      form: {
        pageNum: 1,
        pageSize: 10,
      },
      radio: "",
      roleList: [],
      total: 0,
      list_step5: [],
      loading: false,
      currentData: undefined,
      dataArr: [],
      listRight: [],
      codes: [],
      ids: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      deptOptions: [],
      customPowerForm: {},
      deptCheckStrictly: true,
      deptNodeAll: false,
      deptExpand: true,
      defaultCheckKeys: [],
      systemFieldList: []
    };
  },
  methods: {
    /** 根据角色ID查询部门树结构 */
    getDeptTree(roleId) {
      return deptTreeSelect(roleId).then((response) => {
        this.deptOptions = response.data.depts;
        return response;
      });
    },
    async getList() {
      this.loading = true;
      const res = await listRole(this.form);
      if (res.code === 200) {
        this.roleList = res.rows;
        this.total = res.total;
      }
      this.loading = false;
    },
    handleReset() {
      this.form = {
        pageNum: 1,
        pageSize: 10,
      };
      this.getList();
    },
    handleCurrentChange(val) {
      this.listRight = this.dict.type.sys_data_power;
      this.defaultCheckKeys = []
      this.$nextTick(() => {
        const list = this.dataArr?.filter((item) => item.roleId === val.roleId);
        this.radio = list[0]?.ruleCode
        if (list?.[0]?.ruleCode === 'CUSTOM') {
          this.getDeptTree(val.roleId)
          try {
            this.defaultCheckKeys = list?.[0]?.customIds?.split(',')
          } catch (error) {
            this.defaultCheckKeys = []
          }

        }
        if (list?.[0]?.ruleCode === 'SELF') {
          try {
            const arr = list?.[0]?.customIds?.split(',')
            this.customPowerForm = {fieldLeft:arr[0],fieldRight:arr[1]}
          } catch (error) {
            this.customPowerForm = {}
          }

        }
        this.currentData = val;
      });
    },
    getCurrentRow(key) {
      let isHas = false;
      this.customPowerForm = {}
      if (key.value === 'CUSTOM') {
        this.getDeptTree(this.currentData.roleId)
      }
      if (key.value === 'SELF') {
        this.customPowerForm = { fieldLeft: 'user.getUsername()', fieldRight: 'create_by' }
      }
      this.codes = key.value;
      this.ids = key.raw.dictCode;
      this.dataArr?.forEach((item, index) => {
        if (item.roleId === this.currentData.roleId) {
          item.ruleCode = this.codes;
          item.ruleId = this.ids;
          item.customIds = ''
          isHas = true;
        }
      });
      if (!isHas) {
        this.dataArr.push({
          roleId: this.currentData.roleId,
          ruleCode: this.codes,
          ruleId: this.ids,
          customIds: ''
        });
      }
    },
    deptPowerChange(val, obj) {
      this.dataArr?.forEach((item, index) => {
        if (item.roleId === this.currentData.roleId) {
          item.customIds = obj.checkedKeys.toString()
        }
      });
    },
    handleSelfChange(val) {
      const { fieldLeft, fieldRight } = this.customPowerForm
      this.dataArr?.forEach((item, index) => {
        if (item.roleId === this.currentData.roleId && fieldLeft && fieldRight) {
          item.customIds = `${fieldLeft},${fieldRight}`
        }
      });
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      let treeList = this.deptOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      this.form.deptCheckStrictly = value ? true : false;
    },
  },
  mounted() {
    this.getList();
    if (
      sessionStorage.getItem("pageModel") &&
      JSON.parse(sessionStorage.getItem("pageModel"))?.step5
    ) {
      this.dataArr = JSON.parse(sessionStorage.getItem("pageModel"))?.step5;
      this.systemFieldList = JSON.parse(sessionStorage.getItem("pageModel"))?.step2;
    }
  },
};
</script>
<style lang="scss" scoped>
.dataPower {
  ::v-deep .pagination-container {
    height: 55px;
  }

  .search {
    display: flex;
    align-items: flex-start;
  }

  .main {
    display: flex;
    justify-content: space-between;

    .left {
      width: 48%;
    }

    .right {
      width: 48%;
    }
  }
}

::v-deep .el-radio__label {
  display: none;
}
</style>
